package cn.com.api.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiAddress;
import cn.com.api.entity.ApiCar;
import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiGoods;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_products;
import cn.com.api.entity.ApiT_shops_time;
import cn.com.api.entity.ApiTmember;
import cn.com.api.mapper.ApiAddressMapper;
import cn.com.api.mapper.ApiCarMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiGoodsMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_cityMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiT_shops_timeMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.requestpage.OrderConfirmPage;
import cn.com.api.resultpage.CarOrderPage;
import cn.com.api.resultpage.CarShopPage;
import cn.com.api.resultpage.InitCarPage;
import cn.com.api.resultpage.InitOrderPage;
import cn.com.api.resultpage.OrderGoodsPage;
import cn.com.api.service.ApiCarService;
import cn.com.api.service.ApiOrderService;
import cn.com.api.service.ApiShopsTimeService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.*;

@Service
public class ApiCarServiceImpl implements ApiCarService {
	@Autowired
	private ApiCarMapper apiCarMapper;
	@Autowired
	private ApiGoodsMapper apiGoodsMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiT_shops_timeMapper apiT_shops_timeMapper;
	@Autowired
	private ApiAddressMapper apiAddressMapper;
	@Autowired
	private ApiT_cityMapper cityMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiOrderService apiOrderService;
	@Autowired
	private ApiShopsTimeService apiShopsTimeService;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;

	private static Logger logger = Logger.getLogger(ApiCarServiceImpl.class);

	@Transactional
	@Override
	public void addCar(Map<String, String> params, Map<String, Object> map) {
		/**
		 * 根据u_id、goods_id 判断是否已添加过购物车，已添加过，则对应购物车内物品数量加1
		 */
		String u_id = params.get("u_id");
		Long goods_id = Long.parseLong(params.get("goods_id"));
		Long product_id = Long.parseLong(params.get("product_id"));
		String addFlag = params.get("addFlag");// 0:-1 1:+1
		Integer count = 0;
		if ("1".equals(addFlag)) {
			count = 1;
		} else {
			count = -1;
		}
		// ApiCar car = apiCarMapper.searchCarGoodsByUidAndGoodsId(u_id,
		// goods_id);
		ApiCar car = apiCarMapper.searchCarGoodsByUidAndProductId(u_id, product_id);// product_id
																					// 之后用这个
		// 根据product_id 查询商品数量
		ApiT_products product = apiT_productsMapper.findT_productsById(product_id);
		Integer goodsCount = product.getStore();
		boolean flag = true;
		if (car != null) {
			// 增加商品数量
			Integer carCount = car.getCount();
			if (count == -1 && carCount == 1) {// 购物车数量减少---不校验库存
				apiCarMapper.updateCarStatus(car.getId(), 1);
			} else {
				Integer countTemp = carCount + count;
				if (countTemp.compareTo(goodsCount) <= 0) {
					car.setCount(countTemp);
					apiCarMapper.updateCarCount(car);
				} else {
					flag = false;
				}
			}
		} else {
			if (count.compareTo(goodsCount) <= 0) {
				car = new ApiCar();
				car.setGoods_id(goods_id);
				car.setProduct_id(product_id);
				car.setU_id(u_id);
				car.setCount(count);
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				car.setCreate_date(dateFormat.format(now));
				car.setStatus(0);
				// 根据product_id 查询货品 shop_id city_id--存入car表
				car.setShop_id(product.getShop_id());
				car.setCity_id(product.getCity_id());
				apiCarMapper.addCar(car);
			} else {
				flag = false;
			}

		}
		if (flag) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		} else {
			map.put(Utils.RESULT, "0073");
			map.put(Utils.MESSAGE, "库存不足！");
		}

	}

	@Transactional
	@Override
	public void addCar2(Map<String, String> params, Map<String, Object> map) {
		/**
		 * 根据u_id、goods_id 判断是否已添加过购物车，已添加过，则对应购物车内物品数量加1
		 */
		String u_id = params.get("u_id");
		Long goods_id = Long.parseLong(params.get("goods_id"));
		Long product_id = Long.parseLong(params.get("product_id"));
		Integer count = Integer.parseInt(params.get("count"));
		// ApiCar car = apiCarMapper.searchCarGoodsByUidAndGoodsId(u_id,
		// goods_id);
		ApiCar car = apiCarMapper.searchCarGoodsByUidAndProductId(u_id, product_id);// product_id
																					// 之后用这个
		ApiT_products product = apiT_productsMapper.findT_productsById(product_id);
		Integer goodsCount = product.getStore();
		boolean flag = true;
		if (goodsCount != null) {
			if (car != null) {
				// 增加商品数量
				Integer carCount = car.getCount();
				if (count == -1 && carCount == 1) {// 购物车数量减少---不校验库存
					apiCarMapper.updateCarStatus(car.getId(), 1);
				} else {
					Integer countTemp = carCount + count;
					if (countTemp.compareTo(goodsCount) <= 0) {
						car.setCount(countTemp);
						apiCarMapper.updateCarCount(car);
					} else {
						flag = false;
					}
				}
			} else {
				if (count <= goodsCount) {
					car = new ApiCar();
					car.setGoods_id(goods_id);
					car.setProduct_id(product_id);
					car.setU_id(u_id);
					car.setCount(count);
					car.setPrice(product.getPrice());
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					car.setCreate_date(dateFormat.format(now));
					car.setStatus(0);
					// 根据product_id 查询货品 shop_id city_id--存入car表
					car.setShop_id(product.getShop_id());
					ApiShop apiShop = apiShopsMapper.findT_shopsById(product.getShop_id());
					car.setCity_id(apiShop.getC_city_id());
					apiCarMapper.addCar(car);
				} else {
					flag = false;
				}
			}
		} else {
			flag = false;
		}
		if (flag) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		} else {
			map.put(Utils.RESULT, "0073");
			map.put(Utils.MESSAGE, "库存不足！");
		}

	}

	@Override
	public void goCar(Map<String, String> params, Map<String, Object> map) {
		String u_id = params.get("u_id");
		Integer city_id = Integer.parseInt(params.get("city_id"));
		List<ApiCar> list = apiCarMapper.goCar(u_id, city_id, 0);
		// 给购物车的每条记录添加商品和店铺
		// 店铺---商品
		Map<Integer, String> shopids = new HashMap<Integer, String>();
		InitCarPage resultPage = new InitCarPage();
		if (list != null && list.size() > 0) {
			// 先给每个记录添加商品信息和店铺信息+货品信息
			for (ApiCar car : list) {
				ApiGoods goods = apiGoodsMapper.searchGoodsById(car.getGoods_id());
				car.setGoods(goods);
				/** 货品信息 product_id 目前可能为空 */
				ApiT_products product = new ApiT_products();
				if (!Util.isNull(car.getProduct_id())) {
					product = apiT_productsMapper.findT_productsById(car.getProduct_id());
				}
				ApiShop shop = apiShopsMapper.findShopByCid(product.getShop_id().toString());
				car.setShop(shop);
				car.setProduct(product);
			}
			for (ApiCar car : list) {
				Integer shopId = car.getShop().getcId();
				String shopName = car.getShop().getcSname();
				if (shopids.containsKey(shopId)) {
					for (OrderGoodsPage page : resultPage.getOrderGoodsList()) {
						if (shopId.equals(page.getShop_id())) {
							page.getCarList().add(car);
							break;
						}
					}
				} else {
					shopids.put(shopId, null);
					OrderGoodsPage goodsPage = new OrderGoodsPage();
					List<ApiCar> carList = new ArrayList<ApiCar>();
					carList.add(car);
					goodsPage.setShop_id(shopId);
					goodsPage.setShop_name(shopName);
					goodsPage.setCarList(carList);
					resultPage.getOrderGoodsList().add(goodsPage);
				}
			} // JSONArray.fromObject(shopGoods)
			map.put("datas", resultPage);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
			map.put(Utils.MESSAGE, "购物车为空，快点去添加商品吧！");
		}
	}

	@Override
	public void goCarByMap(Map<String, String> params, Map<String, Object> map) {
		HashMap hashMap = new HashMap();
		String u_id = params.get("u_id");
		hashMap.put("u_id", u_id);
		hashMap.put("status", 0);
		// Integer city_id = Integer.parseInt(params.get("city_id"));
		List<ApiCar> list = apiCarMapper.goCarByMap(hashMap);
		// 给购物车的每条记录添加商品和店铺
		// 店铺---商品
		Map<Integer, String> shopids = new HashMap<Integer, String>();
		InitCarPage resultPage = new InitCarPage();
		if (list != null && list.size() > 0) {
			// 先给每个记录添加商品信息和店铺信息+货品信息
			for (ApiCar car : list) {
				ApiGoods goods = apiGoodsMapper.searchGoodsById(car.getGoods_id());
				car.setGoods(goods);
				/** 货品信息 product_id 目前可能为空 */
				ApiT_products product = new ApiT_products();
				if (!Util.isNull(car.getProduct_id())) {
					product = apiT_productsMapper.findT_productsById(car.getProduct_id());
				}
				ApiShop shop = apiShopsMapper.findShopByCid(product.getShop_id().toString());
				car.setShop(shop);
				car.setProduct(product);
			}
			for (ApiCar car : list) {
				Integer shopId = car.getShop().getcId();
				String shopName = car.getShop().getcSname();
				if (shopids.containsKey(shopId)) {
					for (OrderGoodsPage page : resultPage.getOrderGoodsList()) {
						if (shopId.equals(page.getShop_id())) {
							page.getCarList().add(car);
							break;
						}
					}
				} else {
					shopids.put(shopId, null);
					OrderGoodsPage goodsPage = new OrderGoodsPage();
					List<ApiCar> carList = new ArrayList<ApiCar>();
					carList.add(car);
					goodsPage.setShop_id(shopId);
					goodsPage.setShop_name(shopName);
					goodsPage.setCarList(carList);
					resultPage.getOrderGoodsList().add(goodsPage);
				}
			} // JSONArray.fromObject(shopGoods)
			map.put("datas", resultPage);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
			map.put(Utils.MESSAGE, "购物车为空，快点去添加商品吧！");
		}
	}

	@Override
	public void updateCarInfo(Map<String, Object> map) {
		apiCarMapper.modifyCarInfo(map);
	}

	@Transactional
	@Override
	public void updateCar(CarOrderPage carPage) throws Exception {
		Long product_id = carPage.getProduct_id();
		Integer count = carPage.getCount();
		ApiCar car = new ApiCar();
		car.setId(carPage.getC_id());
		car.setStatus(2);// 已成单
		car.setPrice(carPage.getPrice());
		car.setPoints(carPage.getPoints());
		car.setShop_id(carPage.getShop_id());
		apiCarMapper.updateCar(car);
		// erp校验库存是否正确
		ApiT_products product1 = apiT_productsMapper.findT_productsById(product_id);
		logger.error("校验库存是否正确-订单生成前:product_id-" + product_id + "数量-" + product1.getStore());
		int flag = apiT_productsMapper.reduceProductByProductId(product_id, count);
		if (flag != 1) {// 更新失败，抛出异常
			throw new Exception("商品：" + product1.getName() + "库存不足！");
		}
		ApiT_products product2 = apiT_productsMapper.findT_productsById(product_id);
		logger.error("校验库存是否正确-订单生成前后:product_id-" + product_id + "数量-" + product2.getStore());
	}

	@Transactional
	@Override
	public void deleteCar(Integer c_id) {
		apiCarMapper.updateCarStatus(c_id, 1);// 1-已删除
	}

	@Transactional
	@Override
	public void deleteAllCar(String c_ids) {
		if (!Util.isNull(c_ids)) {
			String[] c_idArray = c_ids.split(",");
			if (c_idArray != null && c_idArray.length > 0) {
				apiCarMapper.deleteAllCar(c_idArray, 1);
			}
		}

	}

	@Override
	public List<CarOrderPage> searchCarProductsByCids(String car_ids) {
		List<CarOrderPage> productList = null;
		if (!Util.isNull(car_ids)) {
			String[] car_idsStr = car_ids.split(",");
			List<Integer> idList = new ArrayList<Integer>();
			productList = new ArrayList<CarOrderPage>();
			if (car_idsStr != null && car_idsStr.length > 0) {
				for (String id : car_idsStr) {
					Integer car_id = Integer.parseInt(id);
					idList.add(car_id);
				}
				productList = apiCarMapper.searchCarGoodsByCids(idList);
			}
		}
		return productList;
	}

	@Override
	public void getMyCarCount(Map<String, String> params, Map<String, Object> map) {
		String u_id = params.get("u_id");
		Integer city_id = Integer.parseInt(params.get("city_id"));
		Map<String, Object> results = apiCarMapper.getMyCarCount(u_id, city_id);
		map.put("datas", results);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/**
	 * 根据出入的c_id判断购物记录是否已生成订单 sendDate：校验是否在店铺的营业时间内
	 * address_id:校验是否在配送距离内-----单独的校验接口--点击确定的话，去生产订单 校验是否是1元购商品----1元购
	 * --新用户只能买一次
	 * 
	 * @throws Exception
	 */
	@Override
	public boolean checkProducts(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		boolean flag = true;
		String car_ids = orderConfirmPage.getC_ids();
		String u_id = orderConfirmPage.getU_id();
		if (!Util.isNull(car_ids)) {
			String[] car_idsStr = car_ids.split(",");
			List<Integer> idList = new ArrayList<Integer>();
			if (car_idsStr != null && car_idsStr.length > 0) {
				for (String id : car_idsStr) {
					Integer car_id = Integer.parseInt(id);
					idList.add(car_id);
				}
				List<ApiCar> list = apiCarMapper.checkHasOrder(idList);
				if (list != null && list.size() > 0) {
					flag = false;
					ApiCar car = list.get(0);
					String msg = car.getGoodsName() + " " + car.getPdt_spec() + " " + car.getUnit();
					map.put(Utils.RESULT, "0080");
					map.put(Utils.MESSAGE, msg + "已生成订单！");
				}

				// 校验库存前先更新Erp库存
				list = apiCarMapper.checkStock(idList);
				System.out.println("校验库存数量：" + list + "-数量：" + list.size());
				if (flag && list != null && list.size() > 0) {
					flag = false;
					ApiCar car = list.get(0);
					String msg = car.getGoodsName() + " " + car.getPdt_spec() + " " + car.getUnit();
					map.put(Utils.RESULT, "0073");
					map.put(Utils.MESSAGE, msg + "库存不足！");
				}
				// 校验商品是否下架--goods表 status 无需校验 --一般没有库存才下架

				/**
				 * 校验是否是1元购商品-- 不是--true 是--是否有过1元购订单
				 */
				list = apiCarMapper.checkOneGoods(idList);
				if (flag && list != null && list.size() > 0) {
					// 是1元购商品---判断是否生成过1元购订单
					ApiCar car = list.get(0);
					String msg = car.getGoodsName() + " " + car.getPdt_spec() + " " + car.getUnit();

					List<ApiDingDan> dingDanList = apiDingDanMapper.searchOneGoodsOrders(u_id);
					if (dingDanList != null && dingDanList.size() > 0) {
						flag = false;
						map.put(Utils.RESULT, "0074");
						map.put(Utils.MESSAGE, "您好，" + msg + "新人特惠1元购商品只能购买1次");
					} else {
						if (list.size() == 1 && list.get(0).getCount() == 1) {//

						} else {
							flag = false;
							map.put(Utils.RESULT, "0075");
							map.put(Utils.MESSAGE, "您好，" + msg + "新人特惠1元购商品只能购买1件");
						}
					}

				}
			}
		}
		return flag;
	}

	@Override
	public boolean checkCarOneGoods(Map<String, String> params, Map<String, Object> map) {
		boolean flag = true;
		String u_id = params.get("u_id");
		String product_id = params.get("product_id");
		Integer product_count = Integer.valueOf(params.get("count"));
		// 1-校验该商品是否是1元购商品
		Integer count = apiCarMapper.checkIsOneGoods(product_id);

		// 2-该商品是1元购商品，校验是否存在1元购订单(1,5)---不存在放行
		if (count > 0) {
			List<ApiDingDan> dingDanList = apiDingDanMapper.searchOneGoodsOrders(u_id);
			// 3-存在1元购订单，提示已下过1元购订单
			if (dingDanList != null && dingDanList.size() > 0) {
				flag = false;
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "已下过1元购订单！");
			} else {
				// 4-不存在1元购订单，购物车是否存在1元购商品--0有效的
				Integer count2 = apiCarMapper.checkCarHasOneGoods(u_id);
				if (count2 > 0) {
					// 5-购物车存在1元购商品，提示--某分站已添加过1元购商品到购物车
					flag = false;
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "购物车已添加过1元购商品！");
				} else {
					// 6-购物车不存在1元购商品，看数量>1 提示1元购商品只允许买1件
					if (product_count > 1) {
						flag = false;
						map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
						map.put(Utils.MESSAGE, "1元购商品只能购买1件");
					}
				}
			}
		}
		return flag;
	}

	@Override
	public boolean checkProductsCharge(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		boolean flag = true;
		String car_ids = orderConfirmPage.getC_ids();
		if (!Util.isNull(car_ids)) {
			String[] car_idsStr = car_ids.split(",");
			List<Integer> idList = new ArrayList<Integer>();
			if (car_idsStr != null && car_idsStr.length > 0) {
				for (String id : car_idsStr) {
					Integer car_id = Integer.parseInt(id);
					idList.add(car_id);
				}
				List<ApiCar> list = apiCarMapper.checkHasOrder(idList);
				if (list != null && list.size() > 0) {
					flag = false;
					ApiCar car = list.get(0);
					String msg = car.getGoodsName() + " " + car.getPdt_spec() + " " + car.getUnit();
					map.put(Utils.RESULT, "0080");
					map.put(Utils.MESSAGE, msg + "已生成订单！");
				}
				list = apiCarMapper.checkStock(idList);
				if (list != null && list.size() > 0) {
					flag = false;
					ApiCar car = list.get(0);
					String msg = car.getGoodsName() + " " + car.getPdt_spec() + " " + car.getUnit();
					map.put(Utils.RESULT, "0073");
					map.put(Utils.MESSAGE, msg + "库存不足！如需继续充值，请到账户中心充值！");
				}
			}
		}
		return flag;
	}

	@Override
	public boolean checkSendTime(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		boolean flag = true;
		String c_ids = orderConfirmPage.getC_ids();
		String product_ids = orderConfirmPage.getProduct_ids();
		String act_ids = orderConfirmPage.getAct_ids();
		InitOrderPage orderPage = null;
		if (!Util.isNull(c_ids)) {
			orderPage = apiOrderService.getShopListByCids(c_ids);
		}
		if (!Util.isNull(product_ids)) {
			orderPage = apiOrderService.getProductListByproductids(product_ids);
		}
		if (!Util.isNull(act_ids)) {
			orderPage = apiOrderService.getProductListByactids(act_ids);
		}
		List<CarShopPage> shopList = orderPage.getShopList();
		/**
		 * 一个店铺一个店铺校验 有配送日期，且格式正确-- 1-先判断店铺是否打烊 2-再判断是否在店铺营业时间内
		 */
		// 判断是否有店铺 下线 或 已打烊
		if (flag && shopList != null && shopList.size() > 0) {
			for (CarShopPage shopPage : shopList) {
				ApiShop shop = apiShopsMapper.findT_shopsById(shopPage.getShop_id());
				if (shop != null) {
					Integer enable = shop.getcEnable();
					Integer is_out = shop.getIs_out();
					Integer is_open = shop.getIs_open();
					if (is_out != null && 1 == is_out) {
						flag = false;
						map.put(Utils.RESULT, "0082");
						map.put(Utils.MESSAGE, "店铺：" + shopPage.getShop_name() + "未上线！");
						break;
					}
					if (enable == null || 0 == enable) {
						flag = false;
						map.put(Utils.RESULT, "0082");
						map.put(Utils.MESSAGE, "店铺：" + shopPage.getShop_name() + "未审核通过！");
						break;
					}

					if (is_open != null && 0 == is_open) {
						flag = false;
						map.put(Utils.RESULT, "0082");
						map.put(Utils.MESSAGE, "店铺：" + shopPage.getShop_name() + "已打烊！");
						break;
					} else {
						if (!apiShopsTimeService.checkNowDateInShopTime(shopPage.getShop_id())) {
							flag = false;
							map.put(Utils.RESULT, "0082");
							map.put(Utils.MESSAGE, "店铺：" + shopPage.getShop_name() + "已打烊！");
							break;
						}
					}
				}
			}
		}
		if (flag && shopList != null && shopList.size() > 0) {
			String ziSendDate1 = "";// 数据库自营配送时间
			String sendDate1 = "";// 数据库非自营配送时间
			String zi_sendTiem_str = startOnLoadService.dictionaryMap().get("TRANSIT_TIME_ZI");// --自营的配送时间
			String sendTiem_str = startOnLoadService.dictionaryMap().get("TRANSIT_TIME");// 非自营的配送时间
			// 当前时间转换成秒，再加上分钟的秒数--再转化为日期
			Integer zi_sendTiem_minute = Integer.parseInt(zi_sendTiem_str);
			Integer sendTiem_minute = Integer.parseInt(sendTiem_str);
			Date nowDate = new Date();
			long nowDate_long = nowDate.getTime();
			long zi_start_long = nowDate_long + (zi_sendTiem_minute - 30) * 60 * 1000;
			long zi_end_long = nowDate_long + zi_sendTiem_minute * 60 * 1000;

			long start_long = nowDate_long;// 从当前时间开始下单判断，最终 +
											// (sendTiem_minute-30)*60*1000;
			// long start_long_final = nowDate_long +
			// (sendTiem_minute-30)*60*1000;//配送时间要不要存成---半个小时的区间
			long end_long = nowDate_long + sendTiem_minute * 60 * 1000;
			SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

			Date zistartDate1 = new Date(zi_start_long);
			Date ziendDate1 = new Date(zi_end_long);

			Date startDate1 = new Date(start_long);
			Date endDate1 = new Date(end_long);
			ziSendDate1 = dateFormat2.format(zistartDate1) + "-" + dateFormat2.format(ziendDate1).substring(11);
			sendDate1 = dateFormat2.format(startDate1) + "-" + dateFormat2.format(endDate1).substring(11);
			System.out.println("自营默认配送时间：" + ziSendDate1);
			System.out.println("非自营默认配送时间：" + sendDate1);

			// 1，一个店铺的配送时间，没有赋值数据库配置的,2，配送时间与营业时间比较
			Map<Integer, String> sendTimeMap = orderConfirmPage.getSendTimeMap();
			for (CarShopPage shopPage : shopList) {
				String shopSendDate = "";
				Integer shop_id = shopPage.getShop_id();
				if (sendTimeMap != null && sendTimeMap.size() > 0) {
					if (sendTimeMap.containsKey(shop_id)) {
						shopSendDate = sendTimeMap.get(shop_id);
					}
				} else {
					sendTimeMap = new HashMap<Integer, String>();
				}
				if (Util.isNull(shopSendDate)) {
					// 赋值数据库默认值--先判断店铺自营与否
					if (1 == shopPage.getIs_ziying()) {// 自营
						shopSendDate = ziSendDate1;
						sendTimeMap.put(shop_id, ziSendDate1);
					} else {
						shopSendDate = sendDate1;
						sendTimeMap.put(shop_id, sendDate1);
					}
				}
				System.out.println("该店铺的配送时间：shop_id-" + shop_id + "--配送时间：" + shopSendDate);
				String[] timeArray = shopSendDate.split(" ");
				String firstDate = timeArray[0].trim();// 2015-11-10
				String secondDate = timeArray[1].trim();// 10:00-10:30
				String[] secondArray = secondDate.split("-");
				if (secondArray != null && secondArray.length > 0) {
					String d1 = secondArray[0] + ":00";
					String d2 = secondArray[1] + ":00";
					Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(firstDate + " " + d1);
					Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(firstDate + " " + d2);
					// 非自营店的话，先校验是否在分站的营业时间内
					if (0 == shopPage.getIs_ziying()) {
						//
						ApiT_city city = cityMapper.findT_cityById(shopPage.getCarList().get(0).getCity_id());
						String openTime = city.getOpen_time();
						boolean shopTimeFlag = false;// 不满足
						if (!Util.isNull(openTime)) {
							String openTimeArray[] = openTime.split("--");
							String start_time = openTimeArray[0];
							String end_time = openTimeArray[1];
							// 开始结束时间
							Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.parse(firstDate + " " + start_time + ":00");
							// 结束时间
							Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.parse(firstDate + " " + end_time + ":00");
							// 配送开始时间大于等于startDate 小于endDate
							// 配送结束时间大于startDate 小于等于endDate---满足配送时间--结束此次循环
							if (date1.compareTo(startDate) >= 0 && date1.compareTo(endDate) < 0) {
								shopTimeFlag = true;
							}
							if (date2.compareTo(startDate) > 0 && date2.compareTo(endDate) <= 0) {
								shopTimeFlag = true;
							}
						}
						if (!shopTimeFlag) {// 该店铺要求的配送时间 不在分站营业时间内--提示
							flag = false;
							map.put(Utils.RESULT, "0081");
							// map.put(Utils.MESSAGE,
							// "店铺："+shopPage.getShop_name()+"配送时间不在"+city.getName()+"分站的营业时间内，请选择配送时间！");
							map.put(Utils.MESSAGE, shopPage.getShop_id());
							break;
						}
					}

					List<ApiT_shops_time> shopTimeList = apiT_shops_timeMapper
							.findT_shops_timeByShopId(shopPage.getShop_id().toString());
					if (shopTimeList != null && shopTimeList.size() > 0) {
						ApiT_shops_time shopTime = shopTimeList.get(0);
						String[] start_time = shopTime.getStart_time().split(",");
						String[] end_time = shopTime.getEnd_time().split(",");
						if (start_time != null && start_time.length > 0) {
							int length = start_time.length;
							boolean shopTimeFlag = false;// 不满足
							for (int i = 0; i < length; i++) {
								// 开始结束时间
								Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
										.parse(firstDate + " " + start_time[i] + ":00");
								// 结束时间
								Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
										.parse(firstDate + " " + end_time[i] + ":00");
								// 配送开始时间大于等于startDate 小于endDate
								// 配送结束时间大于startDate
								// 小于等于endDate---满足配送时间--结束此次循环
								if (date1.compareTo(startDate) >= 0 && date1.compareTo(endDate) < 0) {
									shopTimeFlag = true;
									break;
								}
								if (date2.compareTo(startDate) > 0 && date2.compareTo(endDate) <= 0) {
									shopTimeFlag = true;
									break;
								}
							}
							if (!shopTimeFlag) {// 该店铺要求的配送时间 不在营业时间内--提示
								flag = false;
								map.put(Utils.RESULT, "0081");
								// map.put(Utils.MESSAGE,
								// "店铺："+shopPage.getShop_name()+"配送时间不在营业时间内，请选择配送时间！");
								map.put(Utils.MESSAGE, shopPage.getShop_id());
								break;
							}
						}
					}
				}
			}
			orderConfirmPage.setSendTimeMap(sendTimeMap);
		}
		return flag;
	}

	/** 校验收货地址是否在配送距离内 */
	@Override
	public boolean checkOrderAddress(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		boolean flag = true;

		Integer address_id = orderConfirmPage.getAddress_id();

		ApiAddress addressPage = apiAddressMapper.searchAddressByid(address_id);
		String longitude = addressPage.getLongitude();// 收货地址经度
		String latitude = addressPage.getLatitude();// 收货地址纬度

		String c_ids = orderConfirmPage.getC_ids();
		String product_ids = orderConfirmPage.getProduct_ids();
		String act_ids = orderConfirmPage.getAct_ids();
		InitOrderPage orderPage = null;
		if (!Util.isNull(c_ids)) {
			orderPage = apiOrderService.getShopListByCids(c_ids);
		}
		if (!Util.isNull(product_ids)) {
			orderPage = apiOrderService.getProductListByproductids(product_ids);
		}
		if (!Util.isNull(act_ids)) {
			orderPage = apiOrderService.getProductListByactids(act_ids);
		}
		List<CarShopPage> shopList = orderPage.getShopList();
		if (shopList != null && shopList.size() > 0) {
			// for(CarShopPage shopPage : shopList){
			// List<CarOrderPage> carList = shopPage.getCarList();
			// String shopLongitude = carList.get(0).getLongitude();
			// String shopLatitude = carList.get(0).getLatitude();
			// //商家到收货地址的距离
			// double to_user_distence = Utils.GetDistance(latitude, longitude,
			// shopLatitude, shopLongitude);
			// //查询该店铺的配送距离----每个城市有个配送距离
			// ApiT_city city=
			// cityMapper.findT_cityById(carList.get(0).getCity_id());
			// System.out.println("商家到收货地址的距离："+to_user_distence );
			// System.out.println("该城市的距离："+city.getSend_distance() );
			// if(!Util.isNull(city.getSend_distance()) &&
			// to_user_distence>city.getSend_distance()){//超出配送距离
			// flag = false;
			// shopNameList = shopPage.getShop_name()+",";
			// }
			// }

			// 每个城市有个距离--城市的经纬度 到收货地址的距离
			ApiT_city city = cityMapper.findT_cityById(shopList.get(0).getCarList().get(0).getCity_id());
			String city_latitude = city.getLatitude() + "";
			String city_longitude = city.getLongitude() + "";
			double to_user_distence = Utils.GetDistance(latitude, longitude, city_latitude, city_longitude);
			logger.info("生成订单前校验收货地址的距离：" + "城市：" + city.getName() + "到收货地址" + addressPage.getAddress() + "的距离："
					+ to_user_distence);
			if (!Util.isNull(city.getSend_distance()) && to_user_distence > city.getSend_distance()) {// 超出配送距离
				flag = false;
			}
		}
		if (!flag) {
			String message = "配送地址超出配送距离，请修改收货地址!";
			map.put(Utils.RESULT, "0083");
			map.put(Utils.MESSAGE, message);
		} else {
			map.put(Utils.RESULT, "0000");
			map.put(Utils.MESSAGE, "success");
		}
		return flag;
	}

	/** 积分兑换-校验积分是否充足 */
	@Override
	public boolean checkOrderPoints(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		boolean flag = true;
		String u_id = orderConfirmPage.getU_id();
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		Integer myPoints = member.getcJf();

		String act_ids = orderConfirmPage.getAct_ids();
		InitOrderPage orderPage = apiOrderService.getProductListByactids(act_ids);
		Integer orderPoints = orderPage.getSumPoints();

		if ((myPoints != null && orderPoints != null && orderPoints.compareTo(myPoints) > 0) || myPoints == null) {// 积分不充足
			flag = false;
			map.put(Utils.RESULT, "0084");
			map.put(Utils.MESSAGE, "积分不足！");
		}

		return flag;
	}

	public ApiCar findApiCarById(Integer car_id) {
		return apiCarMapper.findApiCarById(car_id);
	}

	public void updateCar(ApiCar car) {
		apiCarMapper.updateCar(car);
	}

	@Override
	public Map<String, Object> addBuyCard(ApiCar apiCar) {
		Map<String, Object> map=new HashMap<>();
		ApiT_products product = apiT_productsMapper.findT_productsById(apiCar.getProduct_id());
		if (product.getStore()<apiCar.getCount()) {
			map.put(Utils.RESULT,"0073");
			map.put(Utils.MESSAGE, "库存不足！");
		}else {
			apiCarMapper.addCar(apiCar);
			map.put("id", apiCarMapper.getMaxIdByUserId(apiCar.getU_id()));
			map.put(Utils.RESULT,Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
		}
		return map;
	}

	@Override
	public void delCarById(int id) {
		apiCarMapper.delCarById(id);
	}

	@Override
	public void delAllCarByUserId(String userId) {
		apiCarMapper.delAllCarByUserId(userId);
	}
	
	
	@Override
	public Map<String, Object> updCarCount(ApiCar apiCar) {
		Map<String, Object> map=new HashMap<>();
		ApiT_products product = apiT_productsMapper.findT_productsById(apiCar.getProduct_id());
		if (apiCar.getCount()>product.getStore()) {
			map.put(Utils.RESULT,"0073");
			map.put(Utils.MESSAGE, "库存不足！");
		}else {
			apiCarMapper.updateCarCount(apiCar);
			map.put("id", apiCar.getId());
			map.put(Utils.RESULT,Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
		}
		return map;
	}

	@Override
	public List<Map<String, Object>> seeMycart(String userId) {
		// TODO Auto-generated method stub
		return  apiCarMapper.seeMyCart(userId);
	}
	
	
	@Override
	public List<ApiCar> showMyChose(List<String>list) {
		// TODO Auto-generated method stub
		return  apiCarMapper.showMyChose(list);
	}

	@Override
	public List<ApiCar> getCarInfoByCarIds(List<String>list) {
		// TODO Auto-generated method stub
		return apiCarMapper.getCarInfoByCarIds(list);
	}

	@Override
	public ApiCar getApiCarByCondition(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return apiCarMapper.getApiCarByCondition(map);
	}

	@Override
	public void removeOverDueGoods(String userId,String currentDate,String currentHour) {
		// TODO Auto-generated method stubd
		apiCarMapper.removeOverDueGoods(userId,currentDate,currentHour);
		
	}

	@Override
	public void updateCarStatusByCarId(String carId, String status) {
		// TODO Auto-generated method stub
		apiCarMapper.updateCarByCarId(carId, status);
	}

	@Override
	public void updateCardStatusByList(List<String> list, String status) {
		apiCarMapper.updateCardStatusByList(list, status);
		
	}

	@Override
	public void updateCarStatusByUserId(String userId, String status) {
		// TODO Auto-generated method stub
		apiCarMapper.updateCarByUserId(userId, status);
	}

}
